package com.qyxx.designer.miniweb.service;

import java.io.*;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.qyxx.designer.modules.mapper.JaxbMapper;
import com.qyxx.designer.modules.utils.EncryptAndDecryptUtils;
import com.qyxx.jwp.menu.Menu;


/**
 * 
 * @author Administrator
 *
 */
@Component
public class ZtreeMenuManager {

	private static Logger logger = LoggerFactory.getLogger(ZtreeMenuManager.class);
	
	private JaxbMapper jaxb = new JaxbMapper(Menu.class);
	
	public final static String ENCODING = "UTF-8";
	
	public final static String MODULE_PATH = "E:/space/eclipseSpace/idesigner/config/";
		
	private boolean flag=false;
	/**
	 * 保存menu对象到xml文件
	 * @param menu 树形菜单Menu对象
	 * @param fildPath 保存的路径
	 */
	public void saveMenu(Menu menu, String filePath) {
		String xml = jaxb.toXml(menu, ENCODING);
		xml = EncryptAndDecryptUtils.aesEncrypt(xml, "");
		File file = new File(filePath + "menu.xml");
		try {
			FileUtils.writeStringToFile(file, xml, ENCODING);
		} catch (IOException e) {
			throw new ServiceException("写文件时出现异常", e);
		}
	}
	/**
	 * 修改menu对象到xml文件
	 * @param newPath 新的帐套路径
	 * @param oldPath 旧的帐套路径
	 */
	public void changeMenu(String newPath, String oldPath) {
		File oldFile = new File(oldPath); 
		File newFile =new File(newPath);
		if(!oldFile.getAbsolutePath().startsWith(newFile.getAbsolutePath())) {
			try {
				FileUtils.moveFileToDirectory(oldFile, newFile, true);
			} catch (IOException e) {
				throw new ServiceException("剪切文件时出现异常(可能源文件不存在)", e);
			}
		}
	}
	
	/**
	 * 根据key读取xml文件转成menu对象
	 * @param fildPath 删除文件的路径
	 * @return
	 */
	public Menu getMenu(String filePath) {
		String xml = null;
		try {
			File File = new File(filePath+ "menu.xml");
				 xml = FileUtils.readFileToString(File, ENCODING);													
				 xml =  EncryptAndDecryptUtils.aesDecrypt(xml, "");
			Menu menus = jaxb.fromXml(xml);
			return menus;
		} catch (IOException e) {
			throw new ServiceException("读文件时出现异常", e);
		} catch (Exception e) {
			throw new ServiceException("", e);
		}
	}
	
	/**
	 *	根据传过来地址删除文件或者文件夹
	 */
	public boolean deleteFolder(String sPath) {   
		File file = new File(sPath);   
		boolean flag = true;
		if(file.isFile()){
			flag = file.delete();
		}else{
			try {
				FileUtils.deleteDirectory(file);				
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				flag = false;
			}
			
		}
		return flag;
		
	}  
	
}
